package main

import (
	"database/sql"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

var (
	mysql *sql.DB
)

const (
	QueryCodeSQL  = "SELECT * FROM account WHERE code=?"
	InsertCodeSQL = "INSERT INTO account(code,ctime) VALUES(?,?)"
)

func InitMysql(info string, max int) (err error) {
	mysql, err = sql.Open("mysql", info)
	if err != nil {
		return err
	}

	mysql.SetMaxOpenConns(max)
	mysql.SetMaxIdleConns(max / 2)
	return err
}

func CloseMysql() {
	if mysql != nil {
		mysql.Close()
	}
}

func QueryCode(code string) (info *AccountInfo, err error) {
	stmt, err := mysql.Prepare(QueryCodeSQL)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	info = &AccountInfo{}
	if err := stmt.QueryRow(code).Scan(
		&info.Uid,
		&info.Code,
		&info.Platform,
		&info.CTime,
		&info.MTime); err != nil {
		return info, err
	}
	return info, nil
}

func InsertCode(code string) (int64, error) {
	stmt, err := mysql.Prepare(InsertCodeSQL)
	if err != nil {
		return -1, err
	}
	defer stmt.Close()

	now := time.Now().Unix()

	result, err := stmt.Exec(code, now)
	if err != nil {
		return -1, err
	}

	return result.LastInsertId()
}
